package com.organization.services

import org.springframework.context.i18n.LocaleContextHolder
import org.springframework.stereotype.Service
import org.springframework.beans.factory.annotation.Autowired
import java.sql.Timestamp
import javax.validation.ConstraintViolation

/**
 * Created with IntelliJ IDEA.
 * User: inester
 * Date: 09.07.12
 * Time: 9:29
 * To change this template use File | Settings | File Templates.
 */
@Service
class CommonService {

    public static final Map badResponse = [success: "false"]
    public static final Map goodResponse = [success: "true"]

    public static final String depNodeStr = "Department_"
    public static final String projNodeStr = "Project_"
    public static final String emplNodeStr = "Employee_"

    //inject spring bean for generate error messages
    @Autowired
    def messageSource

    //convert json string date to java Date
    def convertDateFromJson(String date){
        Date d = date?(new Date().parse("yyyy-MM-dd", date)):null
        if (d){
            return new Timestamp(d.getTime());
        }
        return null
    }

    //parse domain erros map to extjs form errors format
    def parseErrorsFromDomain(domainErrors){
        def errors = [:]
        if (domainErrors)
            domainErrors.each{errors.putAll()}
            domainErrors.allErrors.each{errors.putAt(it.field,messageSource.getMessage(it,LocaleContextHolder.locale))}
        //use success: false without quotes! it's important for extjs form, wich would be show errors if logical value of success key is false
        return [success: false, "errors": errors]
    }

    //convert "nodetype_nodeId" to "nodeId"
    int nodeIdToDbId(nodeId){
        nodeId.replaceAll("[a-zA-Z/_]","") as int
    }

    def parseConstraintsFromDomain(Set<ConstraintViolation<?>> constraintViolations){
        def errors = [:]
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            errors.putAt(constraintViolation.getPropertyPath().toString(),constraintViolation.getMessage())
        }
        //use success: false without quotes! it's important for extjs form, wich would be show errors if logical value of success key is false
        return [success: false, "errors": errors]
    }
}
